package com.meeting.meetingroom_api.controller;

import com.meeting.meetingroom_api.dto.PaymentDto;
import com.meeting.meetingroom_api.dto.PaymentInitiateDto;
import com.meeting.meetingroom_api.dto.*;
import com.meeting.meetingroom_api.service.PaymentService;
import com.meeting.meetingroom_api.security.UserDetailsImpl;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
// import org.springframework.security.access.prepost.PreAuthorize;
// import org.springframework.security.core.annotation.AuthenticationPrincipal;
// import com.meeting.meetingroom_api.security.UserDetailsImpl;

@RestController
@RequestMapping("/api/payments")
public class PaymentController {

    private final PaymentService paymentService;

    @Autowired
    public PaymentController(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @PreAuthorize("hasRole('CUSTOMER')")
    @PostMapping("/initiate")//已测试
    public ResponseEntity<?> initiatePayment(
            @RequestBody PaymentInitiateDto initiateDto,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        try {
            Object paymentResponse = paymentService.initiatePayment(initiateDto, currentUser.getId());
            // The response could be a redirect URL (String) or JSON data for client SDK
            return ResponseEntity.ok(paymentResponse);
        } catch (IllegalStateException | SecurityException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (EntityNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        }
    }
    //将会议室改为Booked前，先判断是否有已有其它活跃订单正在待支付，会议室改为locked，正在使用，会议室改为in_use，否则为booked。
    @PreAuthorize("hasRole('CUSTOMER')")
    @PostMapping("/confirm/{bookingId}")//已测试
    public ResponseEntity<?> confirmPayment(
            @PathVariable Integer bookingId,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        try {
            PaymentDto paymentDto = paymentService.confirmPayment(bookingId, currentUser.getId());
            return ResponseEntity.ok(paymentDto);
        } catch (IllegalStateException | SecurityException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (EntityNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        }
    }

    @PreAuthorize("hasAnyRole('CUSTOMER', 'EMPLOYEE', 'ADMIN')")
    @GetMapping("/booking/{bookingId}/status")
    public ResponseEntity<PaymentDto> getPaymentStatus(
            @PathVariable Integer bookingId,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        // Add logic to ensure customer can only access their own payment status
        // This validation should be done in the service layer
        try {
            PaymentDto paymentDto = paymentService.getPaymentStatusByBookingId(bookingId);
            return ResponseEntity.ok(paymentDto);
        } catch (EntityNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
    
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/booking/{bookingId}/refund")//用不上，员工通过后立即退款
    public ResponseEntity<PaymentDto> processRefund(
            @PathVariable Integer bookingId,
            @RequestParam String reason,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
         try {
            PaymentDto paymentDto = paymentService.processRefund(bookingId, reason, currentUser.getId());
            return ResponseEntity.ok(paymentDto);
        } catch (IllegalStateException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); // Or a DTO with error message
        } catch (EntityNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
}